package com.ym521.imgcrop.callback;

import static com.ym521.imgcrop.base.Constant.*;

import android.content.Context;
import android.content.Intent;

import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ym521.imgcrop.base.CropRequest;
import com.ym521.imgcrop.base.CropResult;
import com.ym521.imgcrop.base.CropResultCode;
import com.ym521.imgcrop.base.CropType;
import com.ym521.imgcrop.crop.CircleCropActivity;
import com.ym521.imgcrop.crop.GridCropActivity;
import com.ym521.imgcrop.crop.RectCropActivity;
import com.ym521.imgcrop.crop.SelectCropActivity;

/**
 * @author Ym
 * E-mail: 2435970206@qq.com
 * createTime:2023/12/29
 * explain: 裁剪图片 回调
 */
public class CropActivityResult extends ActivityResultContract<CropRequest, CropResult> {
    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, CropRequest input) {
        Intent intent = null;
        if (input.getCropType() == CropType.CIRCLE_CROP.getType()) {
            intent = new Intent(context, CircleCropActivity.class);
            intent.putExtra(REQUEST_KEY, input);
            return intent;
        }
        if (input.getCropType() == CropType.GRID_CROP.getType()) {
            intent = new Intent(context, GridCropActivity.class);
            intent.putExtra(REQUEST_KEY, input);
            return intent;
        }
        if (input.getCropType() == CropType.RECT_CROP.getType()) {
            intent = new Intent(context, RectCropActivity.class);
            intent.putExtra(REQUEST_KEY, input);
            return intent;
        }
        if (input.getCropType() == CropType.SELECT_RECT_CROP.getType()) {
            intent = new Intent(context, SelectCropActivity.class);
            intent.putExtra(REQUEST_KEY, input);
            return intent;
        }
        return intent;
    }

    @Override
    public CropResult parseResult(int resultCode, @Nullable Intent intent) {
        if (intent == null) {
            return new CropResult(CropResultCode.FAIL, null, "");
        }
        String extra = intent.getStringExtra(REQUEST_EXTRA);
        extra = extra == null ? "" : extra;
        if (resultCode == CropResultCode.SUCCESS.getCode()) {
            String path = intent.getStringExtra(CROP_PATH_KEY);
            path = path == null ? "" : path;
            return new CropResult(path.isEmpty() ? CropResultCode.FAIL : CropResultCode.SUCCESS, path, extra);
        }
        if (resultCode == CropResultCode.CANCEL.getCode()) {
            return new CropResult(CropResultCode.CANCEL, null, extra);
        }
        return new CropResult(CropResultCode.FAIL, null, "");
    }
}
